package com.rjkj.medicalwaste.repository

import androidx.lifecycle.LiveData
import androidx.paging.PagingSource
import androidx.room.Query
import com.rjkj.medicalwaste.bean.GarbageBean
import com.rjkj.medicalwaste.bean.UserBean
import com.rjkj.medicalwaste.database.UserDao
import com.rjkj.medicalwaste.network.retrofit.ApiInterface
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext

class UserRepository(private val userDao: UserDao) {
    /**
     * 更新本地数据的用户表
     */
    suspend fun update(list: List<UserBean>): Int {
        return withContext(IO) {
            if (list.isNotEmpty()) {
                userDao.deleteAllUser()
                userDao.insertUserList(list)
                list.size
            } else
                0

        }
    }

    //更新上传状态
    suspend fun updateState(garbageQRCode: String, state: Int) {
        withContext(IO) {
            userDao.updateState(garbageQRCode, state)
        }
    }

    //获取上传状态
    suspend fun findUpdateState(hospitalId: String, state: Int): List<GarbageBean> =
        withContext(IO) {
            when (state) {
                GarbageBean.collectState ->
                    userDao.findUpdateState1(hospitalId)
                GarbageBean.storeState ->
                    userDao.findUpdateState2(hospitalId)
                GarbageBean.boxState ->
                    userDao.findUpdateState3(hospitalId)
                GarbageBean.outboundState ->
                    userDao.findUpdateState4(hospitalId)
                else -> listOf()
            }

        }


    fun getAllUserPagingSource(): PagingSource<Int, UserBean> = userDao.getAllUser()

    fun getUserByRoleIdPagingSource(roleId: String): PagingSource<Int, UserBean> =
        userDao.findUserByRoleId(roleId)

    /**
     * 根据code查询用户
     * @param code String
     * @return UserBean
     */
    fun findUserByCode(code: String): LiveData<UserBean> = userDao.getUserByCode(code)
    suspend fun findUserByCode2(code: String): UserBean? = withContext(Dispatchers.IO) {
        userDao.getUserByCode2(code)
    }

    companion object {
        @Volatile
        private var instance: UserRepository? = null

        fun getInstance(userDao: UserDao): UserRepository =
            instance ?: synchronized(this) {
                instance
                    ?: UserRepository(userDao).also {
                        instance = it
                    }
            }

    }
}